package org.infodavid.common.impl.persistence;

import javax.persistence.PersistenceException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.infodavid.common.IBuilder;
import org.infodavid.common.dto.ITemplateListItem;
import org.infodavid.common.model.ITemplate;
import org.infodavid.common.model.ModelFactory;
import org.infodavid.common.persistence.TemplateDataService;

/**
 * The Class AbstractTemplateDataService.
 */
public abstract class AbstractTemplateDataService extends TemplateDataService {

	/** The Constant log. */
	private static final Log LOGGER = LogFactory.getLog(AbstractTemplateDataService.class);

	/** The builder. */
	private final IBuilder<ITemplate> builder = ModelFactory.getInstance()
	    .getBuilder(ITemplate.class);

	/**
	 * The Constructor.
	 */
	protected AbstractTemplateDataService() {
		super();
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.persistence.IDataService#create()
	 */
	public ITemplate create() throws InstantiationException {
		return builder.create();
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.persistence.IDataService#copyTo(org.infodavid.common.model.IDataObject,
	 * boolean, boolean)
	 */
	public ITemplate copyTo(final ITemplate from, final boolean deep, final boolean asNew)
	    throws PersistenceException, InstantiationException {
		final boolean isDebugEnabled = LOGGER.isDebugEnabled();

		if (isDebugEnabled) {
			LOGGER.debug("Copying entity from " + from + " using deep = " + deep + ", asNew = " + asNew);
		}

		final ITemplate to;

		if (from == null) {
			to = null;
		}
		else {
			to = builder.create();

			copyTo(from, to, asNew);
			to.setName(from.getName());
			to.setMimeType(from.getMimeType());
			CopyUtil.copy(from.getOwnerDetails(), to.getOwnerDetails());
		}

		if (isDebugEnabled) {
			LOGGER.debug("Copied entity = " + to);
		}

		return to;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.infodavid.common.persistence.IDataService#copyListItemTo(org.infodavid.common.model.IDataObject
	 * , boolean, boolean)
	 */
	public ITemplateListItem copyListItemTo(final ITemplateListItem from, final boolean deep,
	    final boolean asNew) throws PersistenceException, InstantiationException {
		final boolean isDebugEnabled = LOGGER.isDebugEnabled();

		if (isDebugEnabled) {
			LOGGER.debug("Copying entity from " + from + " using deep = " + deep + ", asNew = " + asNew);
		}

		final ITemplate to;

		if (from == null) {
			to = null;
		}
		else {
			to = builder.create();

			copyTo(from, to, asNew);
			to.setName(from.getName());
			to.setMimeType(from.getMimeType());
			CopyUtil.copy(from.getOwnerDetails(), to.getOwnerDetails());
		}

		if (isDebugEnabled) {
			LOGGER.debug("Copied entity = " + to);
		}

		return to;
	}
}
